import React, { PureComponent, Fragment } from 'react';
import { Card, Form, Row, Input, Select, DatePicker, Button, Table } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
// import lodash from 'lodash';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { LoginStateArray, UserTypeMapper, LoginStateMapper, LoginModelMapper, SorterOrderMapper } from '../../utils/enum';
// import classNames from 'classnames';
import styles from './LoginLog.less';

@connect(({ GlobalEnumModel, LoginLogModel, loading }) => ({
  GlobalEnumModel,
  LoginLogModel,
  queryLoading: loading.effects['LoginLogModel/findByPage'],
}))
@Form.create()
export default class LoginLog extends PureComponent {

  // 数据初始化
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'GlobalEnumModel/allSysName' });
    this.findByPage();
  }

  // 查询数据
  findByPage = (e) => {
    if (e) e.preventDefault();
    const { dispatch, form } = this.props;
    const queryParam = form.getFieldsValue();
    if (queryParam.loginTimeStart) {
      queryParam.loginTimeStart = moment(queryParam.loginTimeStart).format('YYYY-MM-DD 00:00:00');
    }
    if (queryParam.loginTimeEnd) {
      queryParam.loginTimeEnd = moment(queryParam.loginTimeEnd).format('YYYY-MM-DD 23:59:59');
    }
    dispatch({ type: 'LoginLogModel/findByPage', payload: { ...queryParam, pageNo: 0 } });
  }

  // 表格数据过滤或跳页
  handleTableChange = (pagination, _, sorter) => {
    const { dispatch, LoginLogModel } = this.props;
    const queryParam = { ...LoginLogModel.queryParam, pageNo: pagination.current, pageSize: pagination.pageSize };
    // 排序
    if (sorter.field) {
      const sorterMapper = {};
      queryParam.orderField = sorterMapper[sorter.field];
      queryParam.sort = SorterOrderMapper[sorter.order];
    } else {
      queryParam.orderField = undefined;
      queryParam.sort = undefined;
    }
    dispatch({ type: 'LoginLogModel/findByPage', payload: queryParam });
  }

  // 查询表单
  queryForm() {
    const { form: { getFieldDecorator }, queryLoading, GlobalEnumModel: { sysNameList }, LoginLogModel: { queryParam } } = this.props;
    return (
      <Form onSubmit={this.findByPage} layout="inline" className={styles.queryForm}>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="登录系统">
            {getFieldDecorator('sysName', { initialValue: queryParam.sysName })(
              <Select placeholder="登录系统" allowClear={true}>
                {sysNameList.map(sysName => (<Select.Option key={sysName} value={sysName}>{sysName}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="登录名">
            {getFieldDecorator('username', { initialValue: queryParam.username })(
              <Input placeholder="登录名" />
            )}
          </Form.Item>
          <Form.Item label="手机号">
            {getFieldDecorator('telephone', { initialValue: queryParam.telephone })(
              <Input placeholder="手机号" />
            )}
          </Form.Item>
          <Form.Item label="用户邮箱">
            {getFieldDecorator('email', { initialValue: queryParam.email })(
              <Input placeholder="用户邮箱" />
            )}
          </Form.Item>
        </Row>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="登录状态">
            {getFieldDecorator('loginState', { initialValue: queryParam.loginState })(
              <Select placeholder="登录状态" allowClear={true}>
                {LoginStateArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="登录时间">
            {getFieldDecorator('loginTimeStart', { initialValue: queryParam.loginTimeStart ? moment(queryParam.loginTimeStart) : undefined })(
              <DatePicker placeholder="登录时间-开始" style={{ width: 174 }} />
            )}
          </Form.Item>
          <Form.Item label="登录时间">
            {getFieldDecorator('loginTimeEnd', { initialValue: queryParam.loginTimeEnd ? moment(queryParam.loginTimeEnd) : undefined })(
              <DatePicker placeholder="登录时间-结束" style={{ width: 174 }} />
            )}
          </Form.Item>
          <Form.Item className={styles.formItemButton}>
            <Button type="primary" htmlType="submit" disabled={queryLoading}>查询</Button>
          </Form.Item>
        </Row>
      </Form>
    );
  }

  // 数据表格
  getTable() {
    const { LoginLogModel, queryLoading } = this.props;
    const columns = [
      { title: '登录系统', dataIndex: 'sysName' },
      { title: '登录名', dataIndex: 'username' },
      {
        title: '用户类型', dataIndex: 'userType', render: val => {
          let userType = UserTypeMapper[val];
          if (!userType) userType = UserTypeMapper.error;
          return <span style={{ color: userType.color }}>{userType.label}</span>;
        },
      },
      // { title: '手机号', dataIndex: 'telephone' },
      // { title: '邮箱', dataIndex: 'email' },
      {
        title: '登录状态', dataIndex: 'loginState', render: val => {
          let loginState = LoginStateMapper[val];
          if (!loginState) loginState = LoginStateMapper.error;
          return <span style={{ color: loginState.color }}>{loginState.label}</span>;
        },
      },
      {
        title: '认证模式', dataIndex: 'loginModel', render: val => {
          let loginModel = LoginModelMapper[val];
          if (!loginModel) loginModel = LoginModelMapper.error;
          return <span style={{ color: loginModel.color }}>{loginModel.label}</span>;
        },
      },
      { title: 'Session ID', dataIndex: 'sessionId' },
      { title: '登录IP', dataIndex: 'loginIp' },
      { title: '登录时间', dataIndex: 'loginTime' },
      // { title: '用户登录授权信息', dataIndex: 'authenticationInfo' },
      {
        title: '操作', align: 'center', key: 'action',
        render: (_, record) => {
          if (record.loginState !== 1) return '';
          return (
            <Fragment>
              <a>强行下线</a>
            </Fragment>
          );
        },
      },
    ];
    return (
      <Table
        size="middle"
        bordered={true}
        rowKey={record => record.id}
        columns={columns}
        loading={queryLoading}
        dataSource={LoginLogModel.data}
        pagination={LoginLogModel.pagination}
        onChange={this.handleTableChange}
      />
    );
  }

  render() {
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div>
            {this.queryForm()}
          </div>
          {this.getTable()}
        </Card>
      </PageHeaderLayout>
    );
  }
}
